var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: ['../image/sy/banner.png'],
    userLocation: {
      latitude: 0,
      longitude: 0
    },
    scrollHeight: 0,
    Stores: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight
        })
      },
    })
    wx.request({
      url: 'https://www.limecar.cn/WxApi/ShopList',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        that.setData({
          Stores: res.data
        });
        wx.getLocation({
          type: 'wgs84',
          success: function (res) {
            that.setData({
              "userLocation.latitude": res.latitude,
              "userLocation.longitude": res.longitude
            })
            that.calcAllDis();
          }
        })
      }
    })
  },

  calcAllDis: function () {
    let that = this;
    var Stores = that.data.Stores;
    for (let i = 0; i < Stores.length; i++) {
      let dis = that.getDistance(Stores[i].Latitude, Stores[i].Longitude)
      Stores[i]["dis"] = dis;
    }
    that.setData({ Stores });
  },

  gotoStore: function (options) {
    wx.openLocation({
      latitude: options.currentTarget.dataset.latitude,
      longitude: options.currentTarget.dataset.longitude,
      scale: 18,
      name: options.currentTarget.dataset.name,
      address: options.currentTarget.dataset.address
    })
  },

  getDistance: function (lat2, lng2) {
    var dis = 0;
    var that = this;
    var lat1 = that.data.userLocation.latitude || 0;
    var lng1 = that.data.userLocation.longitude || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

    var r = 6378137;
    dis = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
    return parseInt(dis / 1000);
  },

  SelStore: function (options) {
    app.globalData.storeName = options.currentTarget.dataset.stores;
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  listenSwiper: function (e) {
    //打印信息
    console.log(e)
  }
})